<?php
/**
 * Created by PhpStorm.
 * User: xiong
 * Date: 2018/2/5
 * Time: 16:37
 */

namespace App\Http\Controllers\Auth;


use App\Helper;
use App\Http\Controllers\Controller;
use App\Models\InCode;
use App\Models\User;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    public function show()
    {
        return view('auth.register', ['hasback' => true]);
    }

    public function register(Request $request)
    {
        $rules = [
            'username' => 'required',
            'password' => 'required',
            'invite_code' => 'required',
            'sms_code' => 'required'
        ];
        $user = User::wherePhone($request->username)->first();
        if (!$user) {
            $isCheck = Helper::checkSmsCode($request->username, $request->sms_code);
            if (!$isCheck) {
                return response()->json(['msg' => '验证码错误', 'code' => 400], 200);
            }
            $inCode = InCode::whereCode($request->invite_code)->first();
            if (!$inCode) {
                return response()->json(['msg' => '邀请码错误', 'code' => 400], 200);
            } else {
                $inCode->status = true;
                $insert = [
                    'name' => $request->username,
                    'password' => bcrypt($request->password),
                    'phone' => $request->username,
                    'status' => 0,
                ];
                $user = User::create($insert);
                $inCode->user_id = $user->id;
                $inCode->save();
               \Auth::login($user);
                return response()->json(['msg' => '注册成功', 'code' => 200], 200);
            }
        } else {
            return response()->json(['msg' => '账号已存在，请使用其他手机注册', 'code' => 400], 200);
        }

    }
}